<template>
  <!-- 新增 -->
  <el-dialog
    v-if="visible"
    v-el-drag-dialog
    :title="type === 'add' ? '新增押金单' : '押金编辑'"
    :visible.sync="visible"
    width="80%"
    append-to-body
    @close="reset"
  >
    <!-- 客户信息 -->
    <div class="item">
      <div class="title">
        <span class="title-icon" />
        <span class="title-text">客户信息</span>
      </div>
      <el-form v-if="type === 'add'" ref="csmInfoForm" :model="temp" class="form" :rules="rules" label-position="right" label-width="85px">
        <el-form-item label-width="0" prop="qtype">
          <el-input v-model="param" placeholder="请输入" clearable @clear="clearData">
            <el-select slot="prepend" v-model="qtype" style="width: 100px;" placeholder="请选择">
              <el-option label="电话" value="csmRgPhone" />
              <el-option label="客户编号" value="csmCode" />
              <el-option label="身份证号" value="sfzh" />
            </el-select>
            <el-button slot="append" class="append-search" @click="searchMessage">查询</el-button>
          </el-input>
        </el-form-item>
      </el-form>
      <el-form ref="csmInfoForm" :model="information" class="form" :rules="rules" label-position="right" label-width="85px">
        <el-form-item label="客户编号:">
          <el-input v-model="temp.csmCode" disabled />
        </el-form-item>
        <el-form-item label="名称:">
          <el-input v-model="temp.csmName" disabled />
        </el-form-item>
        <el-form-item label="身份证号:">
          <el-input v-model="temp.sfzh" disabled />
        </el-form-item>
        <el-form-item label="联系电话:" prop="csmPhoneId">
          <el-select v-model="information.csmPhoneId" placeholder="请选择" clearable @change="changePhone">
            <el-option v-for="(v,index) in temp.phoneItems" :key="index" :label="v.csmPhone" :value="v.csmPhoneId" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系地址:" style="width: 66%;">
          <el-select v-model="information.csmAddressId" placeholder="请选择" clearable @change="changeAddress">
            <el-option v-for="(v,index) in temp.addressItems" :key="index" :label="v.csmAddress" :value="v.csmAddressId" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <!-- 押金信息 -->
    <div class="item">
      <div class="title">
        <span class="title-icon" />
        <span class="title-text">押金信息</span>
      </div>
      <el-form ref="csmInfoForm" :model="submit" class="form" :rules="rules" label-position="right" label-width="85px">
        <el-form-item label="押金单号:" prop="depositCode">
          <el-input v-model="submit.depositCode" placeholder="请输入" clearable>
            <el-button slot="append" class="append-search" @click="getNum">获取</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="押瓶机构:" prop="ckOrgSNNo">
          <el-tree-select
            v-model="submit.ckOrgSNNo"
            :clearable="false"
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择押瓶机构',
            }"
            :tree-params=" {
              'default-expand-all': true,
              'expand-on-click-node': false,
              'highlight-current': true,
              props:{
                value:'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData
            }"
            @node-click="selectTreeChange"
          />
        </el-form-item>
        <el-form-item label="收款人:" prop="depReceiver">
          <el-select v-model="submit.depReceiver" placeholder="请选择">
            <el-option v-for="(v,userId) in depReceiver" :key="userId" :label="v.userName" :value="v.userName" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间:" prop="beginDt">
          <el-date-picker
            v-model="submit.beginDt"
            placeholder="选择日期"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="收款方式:" prop="depStatus">
          <el-select v-model="submit.depStatus" placeholder="请选择">
            <el-option v-for="(v,index) in calcTypeMap" :key="index" :label="v.desc" :value="v.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="手续费:">
          <el-input v-model="submit.fee1" />
        </el-form-item>
        <el-form-item label="收据单号:" style="width: 66%;">
          <el-input v-model="submit.billCode" />
        </el-form-item>
        <el-form-item label="支付方式:" prop="paymentMethod">
          <el-select v-model="submit.paymentMethod" placeholder="请选择">
            <el-option v-for="(v,index) in paymentMethodMap" :key="index" :label="v.desc" :value="v.value" />
          </el-select>
        </el-form-item>
        <el-form-item class="block">
          <label slot="label">备注:</label>
          <el-input v-model="submit.remark" type="textarea" :rows="2" maxlength="255" show-word-limit />
        </el-form-item>
      </el-form>
    </div>
    <!-- 押瓶信息 -->
    <div class="item">
      <div class="title">
        <span class="title-icon" />
        <span class="title-text">押瓶信息</span>
      </div>
      <el-form :model="submit" :rules="rules" label-position="right" label-width="80px">
        <el-form-item label="规格型号:" style="width: 70%;" prop="goodsName">
          <el-select ref="goodsName" v-model="gasTank.goodsName" style="width: 40%;" placeholder="请选择" clearable @change="getChange">
            <el-option v-for="(v,index) in gasTank" :key="index" :label="v.goodsName" :value="v.goodsId" />
          </el-select>
          <el-button type="primary" style="width: 70px;" size="mini" @click="addDeposit">添加</el-button>
        </el-form-item>
        <div v-for="(item,index) in tableData" :key="index" class="cardMain">
          <el-card class="card" style="margin-bottom: 8px;">
            <el-form sizi="mini" label-width="50px" class="form">
              <el-form-item label-width="80px" style="width: 25%;" label="规格型号:">
                {{ item.goodsName }}
              </el-form-item>
              <el-form-item style="width: 20%;" label="数量:">
                <el-input-number v-model="item.goodsCount" size="mini" :min="1" @change="handleChangeNum" />
              </el-form-item>
              <el-form-item style="width: 20%;" label="租金:">
                <el-input v-model="item.rental" size="mini" style="width: 80px;" /> 元/个
              </el-form-item>
              <el-form-item size="mini" style="width: 20%;" label="押金:">
                <el-input v-model="item.deposit" style="width: 80px;" /> 元/个
              </el-form-item>
              <el-form-item label-width="80px" style="width: 15%;" label="押金合计:">
                {{ getsum(item,index) }}
              </el-form-item>
              <el-form-item label-width="80px" label="钢瓶号:" style="width: 100%;">
                <el-tag
                  v-for="tag in item.btNoIDS"
                  :key="tag"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag,item)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  ref="saveTagInput"
                  v-model.trim="item.inputValue"
                  class="input-new-tag"
                  size="mini"
                />
                <el-button type="primary" style="width: 70px;" size="mini" @click="handleInputConfirm(item,index)">添加</el-button>
              </el-form-item>
            </el-form>
            <el-button class="del_Btn" type="danger" size="mini" icon="el-icon-delete" style="font-size: 14px;" @click="deleteDate(index)" />
          </el-card>
        </div>
        <el-form-item label="附件上传">
          <el-upload
            ref="upload"
            action="//upload.qiniup.com/"
            multiple
            :data="qiniuData"
            :before-upload="beforeUpload"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :limit="limit"
            :on-exceed="handleExceed"
            :file-list="fileList"
            accept="image/jpeg, image/jpg, image/png"
          >
            <el-button icon="el-icon-upload2" size="small" type="primary" @click="pcUpload">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>

    <!-- <div>
      <el-image
        style="width: 100px; height: 100px;"
        :src="url"
        :preview-src-list="fileList"
      />
    </div> -->

    <span slot="footer" class="dialog-footer">
      <span class="deposit">押金总计：￥{{ AlltotalDeposit() }}</span>
      <el-checkbox v-model="isSeparate" class="depositForm">每个钢瓶生成单独的押金单</el-checkbox>
      <el-button @click="reset">关闭</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </span>

  </el-dialog>
</template>

<script>
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  // import accMul from '@/utils/math'
  import { queryCustomerExact, queryCodeGeneration, queryPayee, queryGasTankList, querySaveDepositList } from '@/api'
  import { queryQiniuyunUploadToken, querySaveUserAnnexListByPc } from '@/api'

  export default {
    name: 'normalr-eceipts-add',
    data() {
      return {
        id: '',
        limit: 1,
        token: '',
        information: { }, // 选择的联系人信息
        qiniuData: { // 这里是直接绑定data的值
          key: '', // 图片名字处理
          token: '', // 七牛云token
          data: {},
          bucket: ' '
        },
        annexList: [],
        url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
        srcList: [
          'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg',
          'https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg'
        ],
        calcTypeMap: [
          { 'value': 0, 'desc': '免租金', 'key': 'NONE' },
          { 'value': 1, 'desc': '按日收费', 'key': 'DAILY' },
          { 'value': 3, 'desc': '按月收费', 'key': 'MONTHLY' },
          { 'value': 4, 'desc': '按半年费', 'key': 'SUBANNUALLY' },
          { 'value': 5, 'desc': '按年收费', 'key': 'ANNUALLY' }
        ],
        paymentMethodMap: [
          { 'value': 1, 'desc': '现金', 'key': 'MONEY' },
          { 'value': 2, 'desc': '微信支付', 'key': 'WECHAT' },
          { 'value': 128, 'desc': '支付宝', 'key': 'ALIPAY' },
          { 'value': 1024, 'desc': '工行支付', 'key': 'ICBCPAY' }
        ],
        type: 'add',
        inputVisible: false,
        visible: false,
        isSeparate: false,
        fileList: [],
        depositDetails: [],
        btNoIDS: [],
        totalDeposit: '',
        totalCount: '',
        depStatus: 0,
        tableData: [],
        goodsData: {},
        i: 1,
        qtype: 'csmCode',
        param: '',
        treeData: [],
        phoneItems: [],
        addressItems: [],
        codeType: 9,
        depReceiver: [],
        gasTank: [],
        orgId: '',
        temp: {
          depositCode: null, // 押金编号
          depReceiver: null // 收款人
        },
        submit: {
          depositCode: null, // 押金编号
          depReceiver: null // 收款人
        },
        rules: {
          ckOrgSNNo: [{ required: true, message: '请选择押瓶机构', trigger: 'change' }],
          csmAddressId: [{ required: true, message: '不能为空', trigger: 'change' }],
          depositCode: [{ required: true, message: '不能为空', trigger: 'change' }],
          userName: [{ required: true, message: '不能为空', trigger: 'change' }],
          beginDt: [{ required: true, message: '不能为空', trigger: 'change' }],
          depStatus: [{ required: true, message: '不能为空', trigger: 'change' }],
          paymentMethod: [{ required: true, message: '不能为空', trigger: 'change' }]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList',
        'userInfo',
        'corpSettingData'
      ])
    },
    async created() {
      await this.getTreeData()
      // this.getQiniuyunUploadToken()
    },
    async mounted() {
      // this.payee()
      this.allNum()
      this.calcType()
    },
    methods: {
      changePhone(val) {
        console.log(val)
        if (!val) {
          this.information.csmPhone = null
          return
        }
        var obj = this.temp.phoneItems.find(l => l.csmPhoneId === val)
        this.information.csmPhone = obj.csmPhone
        console.log(this.information)
      },
      changeAddress(val) {
        console.log(val)
        if (!val) {
          this.information.csmAddress = null
          return
        }
        var obj = this.temp.addressItems.find(l => l.csmAddressId === val)
        this.information.csmAddress = obj.csmAddress
      },

      async pcUpload() {
        if (this.fileList.length === 0) {
          this.$message.info('请选择文件')
          return
        }
        if (this.fileList.length > this.limit) {
          this.$message.warning(`当前用户证件附件可继续上传最大张数：${this.limit}张`)
          return
        }
        const attList = this.fileList.map(item => {
          return {
            sourceName: item.response.key.split('.')[0],
            suffix: item.response.key.split('.')[1],
            url: item.response.key,
            size: item.response.fsize
          }
        })
        await querySaveUserAnnexListByPc({
          id: this.id,
          sysAttachmentList: attList
        })
      },
      beforeUpload(file) {
        const key = `${this.userInfo.corpCode}_${new Date().getTime()}_${file.name}`
        this.qiniuData.key = key
        return this.qiniuData
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前用户证件附件可继续上传最大张数：${this.limit}张，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      },
      handleSuccess(res, file, fileList) {
        this.fileList = fileList
      },
      handleRemove(file, fileList) {
        this.fileList = fileList
      },
      // 获取七牛云上传token
      async getQiniuyunUploadToken() {
        const res = await queryQiniuyunUploadToken()
        this.qiniuData.token = res.data
      },
      // 收费处理
      calcType() {
        if ((this.corpSettingData.sp1 >> 24 & 0x01) === 0x01) {
          this.temp.calcType = 3
        }
      },
      // 获取选中
      getChange(val) {
        var goodsObj = {}
        this.gasTank.forEach((item, i) => {
          if (item.goodsId === val) {
            goodsObj = { ...item }
          }
        })
        console.log(goodsObj, 'obj')
        // console.log(this.goodsData)
        this.goodsData = {
          //  deposit: 0.01,,
          goodsCode: goodsObj.goodsCode,
          goodsCount: 1,
          goodsId: goodsObj.goodsId,
          goodsName: goodsObj.goodsName,
          // rental: 0,
          specCode: goodsObj.specCode,
          specName: goodsObj.specName,
          totalDeposit: 0.01,
          btNoIDS: []
        }
        this.goodsData.deposit = goodsObj.ypFee1 ? (goodsObj.ypFee1 - 1) / 2 / 100 : (goodsObj.cashPledge ? goodsObj.cashPledge : 0)
        this.goodsData.rental = goodsObj.zpFee1 ? (goodsObj.zpFee1 - 1) / 2 / 100 : 0
        console.log(this.goodsData, 'goods')
      },
      // 计算价格
      getsum(item, index) {
        item.totalDeposit = item.deposit * item.goodsCount
        return item.totalDeposit
      },
      // 总数量
      allNum() {
        this.totalCount = this.depositDetails.reduce((num, item) => {
          return num + item.goodsCount
        }, 0)
        return this.totalCount
      },
      // 总押金
      AlltotalDeposit() {
        var num = 0
        this.tableData.forEach(l => {
          num = num + l.totalDeposit
        })
        return num
      },
      // 添加押瓶信息
      addDeposit() {
        if (!this.goodsData.goodsId) {
          return
        }
        var flag = this.tableData.findIndex(l => l.goodsId === this.goodsData.goodsId)
        console.log(flag)
        console.log(this.tableData)
        if (flag >= 0) {
          this.tableData[flag].goodsCount++
          return
        }
        this.tableData.push({ ...this.goodsData })
      },
      // 删除押瓶信息
      deleteDate(index) {
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((val) => {
          this.tableData.splice(index, 1)
          this.$message({ type: 'success', message: '删除成功!' })
        }).catch(() => {
          // this.$message({ type: 'info', message: '已取消删除' })
        })
      },

      // 删除钢瓶号
      handleClose(tag, item) {
        item.btNoIDS.splice(item.btNoIDS.indexOf(tag), 1)
      },
      // 添加钢瓶号
      handleInputConfirm(item, index) {
        const inputValue = item.inputValue
        if (!inputValue) return
        var num = item.btNoIDS.length
        var flag = item.btNoIDS.find(l => l === inputValue)
        if (flag) {
          this.$message.warning('钢瓶号不能重复添加')
          return
        }
        if (num >= item.goodsCount) {
          this.$confirm('瓶号数量和押瓶数量不一致，是否继续保存?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then((val) => {
            item.btNoIDS.push(inputValue)
            item.inputValue = ''
          })
          return
        }

        item.btNoIDS.push(inputValue)
        item.inputValue = ''
      },
      // 收款人
      async payee(orgId) {
        const res = await queryPayee({ orgId })
        this.depReceiver = res.data
      },
      // 钢瓶信息
      async gasTankList(orgId) {
        const res = await queryGasTankList({ orgId })
        // this.gasTank = res.data
        var list = []
        for (var i = 0; i < res.data.length; i++) {
          var goods = res.data[i]
          if ((goods.gdStatus & 1 << 2) > 0) {
            list.push(goods)
          }
        }
        console.log(list, 'list')
        this.gasTank = list
      },
      // 获取所属机构数据
      async getTreeData() {
        // const res = await organizationQueryList({})
        const data = this.orgList.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = await getTreeData(data)
      },
      // 选择所属机构
      async selectTreeChange(value) {
        console.log(value, 'value')
        this.submit.ckOrgSNNo = value.orgSNNo
        this.submit.ckOrgName = value.orgName
        this.submit.ckOrgId = value.orgId
        this.submit.userName = null
        await this.payee(value.orgId)
        await this.gasTankList(value.orgId)
        this.goodsData = {}
        this.tableData = []
      },
      open(temp, type) {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.type = type
            this.param = temp.csmCode
            this.temp = { ...temp }
          }
        })
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      // 查询客户信息
      async searchMessage() {
        if (!this.param) {
          this.$message({
            message: '查询条件不能为空',
            type: 'warning'
          })
          return
        }
        this.$refs.csmInfoForm.resetFields()
        this.tableData = []
        this.submit = {
          depositCode: null, // 押金编号
          depReceiver: null // 收款人
        }
        this.goodsData = {}
        this.temp = {}
        const params = {}
        params[this.qtype] = this.param
        const result = await queryCustomerExact(params)
        if (!result.data) {
          this.$message.error('未搜索到该客户信息')
          return
        }
        this.temp = { ...result.data }
      },
      // 获取单号
      async getNum() {
        const codeType = this.codeType
        const code = {
          codeType
        }
        const result = await queryCodeGeneration(code)
        this.submit.depositCode = result.data
      },
      handleChangeNum() {

      },
      // 保存
      async save() {
        // csmInfoForm desfoForm
        this.$refs.csmInfoForm.validate().then(async(res) => {
          if (res) {
            if (this.tableData.length === 0) {
              this.$message.warning('请添加商品')
              return '请添加商品'
            }
            var depositDetails = JSON.parse(JSON.stringify(this.tableData))
            var num = 0
            depositDetails.forEach(l => {
              l.btNoIDS = l.btNoIDS.join(',')
              num = num + l.goodsCount
            })
            depositDetails = [...depositDetails]

            const params = {
              ...this.submit,
              ...this.information,
              depositDetails,
              csmCode: this.temp.csmCode,
              csmId: this.temp.csmId,
              csmName: this.temp.csmName,
              csmPhone: this.temp.csmPhone,
              isSeparate: Boolean(this.isSeparate),
              totalCount: num,
              calcType: this.temp.calcType || '0',
              totalDeposit: this.AlltotalDeposit()

            }
            const res = await querySaveDepositList(params)
            if (res.success) {
              this.$message.success('保存成功')
              this.reset()
            }
            console.log(params)
          }
        })
      },
      // input属性发生变化 清空数据
      clearData() {
        this.temp.csmCode = ''
        this.temp.csmName = ''
        this.temp.sfzh = ''
        this.information.csmPhoneId = ''
        this.information.csmAddressId = ''
        this.temp.phoneItems = []
        this.temp.addressItems = []
      },
      async add() {
        // await roleAdd(this.temp)
        this.resolve()
        this.visible = false
        this.$message({
          title: '提示',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
      },
      async edit() {
        // await roleUpdate(this.temp)
        this.resolve(this.temp)
        this.visible = false
        this.$message({
          title: '提示',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.$nextTick(() => {
          this.$refs.csmInfoForm.resetFields()
          this.visible = false
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.item {
  margin-bottom: 20px;
  .title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .title-icon {
      display: inline-block;
      width: 4px;
      height: 18px;
      margin-right: 6px;
      background: #01999f;
    }
    .title-text {
      font-family: Microsoft YaHei, Microsoft YaHei-Bold;
      font-size: 14px;
      font-weight: 700;
      color: #01999f;
    }
    .content {
      margin-bottom: 0;
    }
  }
  &:last-child {
    margin-bottom: 0;
  }

  .card {
    position: relative;

    .del_Btn {
      position: absolute;
      top: 0;
      right: 0;
      width: 44px;
      height: 40px;
    }
  }
}

.form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  & /deep/ .el-form-item {
    width: 33%;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}

.dialog-footer {
  .deposit {
    float: left;
    margin-left: 30px;
    font-size: 16px;
    font-weight: 700;
    color: #F26A24;
  }

  .depositForm {
    float: left;
    margin-left: 160px;
    font-size: 14px;
    color: #01999F;
  }
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  // height: 32px;
  // line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
  margin-left: 10px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.cardMain {
  /deep/ .el-card__body {
    padding: 5px;
  }
}

</style>
